<template>
    <el-main>
        <div class="teacher">
            <div class="app-table">
                <div class="app-body">

                    <el-drawer v-model="drawer" title="选择接收人员" :direction="direction" :before-close="handleClose">
                        <el-tree ref="tree" :data="allTeacherList" show-checkbox node-key="value" :props="defaultProps"
                            @check="handleCheckChange" :default-checked-keys="keys" :model-value="keys" />
                        <!-- <template #footer>
                            <div style="flex: auto">
                                <el-button @click="cancelClick">cancel</el-button>
                                <el-button type="primary" @click="confirmClick">confirm</el-button>
                            </div>
                        </template> -->
                    </el-drawer>

                    <div class="title_box">
                        <input type="text" class="titleInput" placeholder="输入标题" v-model="addPbArticleForm.title">
                    </div>
                    <div class="intro_box">
                        <textarea placeholder="请输入简介" v-model="addPbArticleForm.summary"></textarea>
                        <div class="introBtn flex">
                            <img src="../../assets/notice_editicon.png" alt="">
                            <p>编辑简介</p>
                        </div>
                    </div>
                    <div class="contain flex">
                        <div class="switchBox flex">
                            <p>是否展示</p>
                            <el-switch v-model="addPbArticleForm.isDisplayed" @change="changeSwitch" />
                        </div>
                        <div class="switchBox flex">
                            <p>是否置顶</p>
                            <el-switch v-model="addPbArticleForm.isPinned" @change="changeSwitch1" />
                        </div>
                        <div class="switchBox flex">
                            <p>发布日期</p>
                            <el-config-provider :locale="locale">
                                <el-date-picker v-model="addPbArticleForm.publishDate" type="date" style="width: 240px"
                                    placeholder="请选择发布日期" :size="size" @change="changeTime" />
                            </el-config-provider>
                        </div>
                    </div>
                    <!-- <div class="contain flex" @click="drawer = true">
                        <img class="add_img" src="../../assets/notice_addicon.png" alt="">
                        <p class="accept">添加接收人员</p>
                    </div> -->
                    <div class="editorBox">
                        <p>详细内容</p>
                        <Editor v-model="addPbArticleForm.content" :init="init" :disabled="disabled"
                            @onClick="onClick" />
                    </div>

                    <button class="publish" @click="add">保存</button>
                </div>
                <!-- <bottomView /> -->
            </div>
        </div>
    </el-main>
</template>
<script>
import addEditApprovalSealView from "@/components/seal/addEditApprovalSeal.vue";
import { ElConfigProvider, ElMessageBox, ElMessage, } from "element-plus";
import zhCn from "element-plus/lib/locale/lang/zh-cn";
import { httpService } from "@/utils/httpService";
import { Picture as IconPicture, Upload, Stamp } from "@element-plus/icons-vue";
import bottomView from "@/components/bottom.vue";
import { vxRule } from "@/utils/validator";
import { uploadImg, formatTime } from "@/utils/dateFormat"
import { API_BASE_NAME, API_BASE_NAME1 } from "../../constants"
//富文本
//引入tinymce编辑器
import Editor from "@tinymce/tinymce-vue";
//引入方式引入node_modules里的tinymce相关文件文件
import tinymce from "tinymce/tinymce"; //tinymce默认hidden，不引入则不显示编辑器
import "tinymce/themes/silver"; //编辑器主题，不引入则报错
import "tinymce/icons/default"; //引入编辑器图标icon，不引入则不显示对应图标
// 引入编辑器插件
import "tinymce/plugins/advlist"; //高级列表
import "tinymce/plugins/anchor"; //锚点
import "tinymce/plugins/autolink"; //自动链接
import "tinymce/plugins/autoresize"; //编辑器高度自适应,注：plugins里引入此插件时，Init里设置的height将失效
import "tinymce/plugins/autosave"; //自动存稿
import "tinymce/plugins/charmap"; //特殊字符
import "tinymce/plugins/code"; //编辑源码
import "tinymce/plugins/codesample"; //代码示例
import "tinymce/plugins/directionality"; //文字方向
import "tinymce/plugins/emoticons"; //表情
import "tinymce/plugins/fullpage"; //文档属性
import "tinymce/plugins/fullscreen"; //全屏
import "tinymce/plugins/help"; //帮助
import "tinymce/plugins/hr"; //水平分割线
import "tinymce/plugins/image"; //插入编辑图片
import "tinymce/plugins/importcss"; //引入css
import "tinymce/plugins/insertdatetime"; //插入日期时间
import "tinymce/plugins/link"; //超链接
import "tinymce/plugins/lists"; //列表插件
import "tinymce/plugins/media"; //插入编辑媒体
import "tinymce/plugins/nonbreaking"; //插入不间断空格
import "tinymce/plugins/pagebreak"; //插入分页符
import "tinymce/plugins/paste"; //粘贴插件
import "tinymce/plugins/preview"; //预览
import "tinymce/plugins/print"; //打印
import "tinymce/plugins/quickbars"; //快速工具栏
import "tinymce/plugins/save"; //保存
import "tinymce/plugins/searchreplace"; //查找替换
import "tinymce/plugins/tabfocus"; //切入切出，按tab键切出编辑器，切入页面其他输入框中
import "tinymce/plugins/table"; //表格
import "tinymce/plugins/template"; //内容模板
import "tinymce/plugins/textcolor"; //文字颜色
import "tinymce/plugins/textpattern"; //快速排版
import "tinymce/plugins/toc"; //目录生成器
import "tinymce/plugins/visualblocks"; //显示元素范围
import "tinymce/plugins/visualchars"; //显示不可见字符
import "tinymce/plugins/wordcount"; //字数统计


export default {
    name: "ApprovalSealListView",
    props: {
        value: {
            type: String,
            default: "",
        },
        disabled: {
            type: Boolean,
            default: false,
        },
        plugins: {
            type: [String, Array],
            default:
                "print preview searchreplace autolink directionality visualblocks visualchars fullscreen image link media template code codesample table charmap hr pagebreak nonbreaking anchor insertdatetime advlist lists wordcount textpattern autosave ",
        },
        toolbar: {
            type: [String, Array],
            default:
                "fullscreen undo redo restoredraft | cut copy paste pastetext | forecolor backcolor bold italic underline strikethrough link image anchor | alignleft aligncenter alignright alignjustify outdent indent | \
                styleselect formatselect fontselect fontsizeselect | bullist numlist | blockquote subscript superscript removeformat | \
                table media charmap emoticons hr pagebreak insertdatetime print preview | code selectall | indent2em lineheight formatpainter axupimgs",
        },
    },
    data() {
        return {
            schoolName: API_BASE_NAME,
            schoolName1: API_BASE_NAME1,
            type: 0,
            title: "",
            page: 1,
            pageSize: 10,
            total: 0,
            limit: 10,
            list: [],
            allTeacherList: [],
            isDisplayedData: [
                {
                    value: 1,
                    label: '展示',
                },
                {
                    value: 2,
                    label: '不展示',
                },
            ],
            isPinnedData: [
                {
                    value: 1,
                    label: '置顶',
                },
                {
                    value: 2,
                    label: '不置顶',
                },
            ],
            defaultProps: {
                children: 'children',
                label: 'label'
            },
            checkedNodes: [],
            allCheckedNodes: [],
            queryId: '',
            allList: [],
            keys: [],
            switchFlag: true,
            switchFlag1: true,
            drawer: false,
            // formLabelWidth: "80px",
            addPbArticleForm: {
                title: "",
                publishDate: "",
                // allTeacher: "",
                summary: "",
                content: "",
                departmentIds: "",
                teacherNumbers: "",
                isDisplayed: 1,
                isPinned: 2,
            },
            // 校验规则
            addPbArticlerules: {
                title: vxRule(true, null, "blur"),
                publishDate: vxRule(true, null, "blur"),
                summary: vxRule(true, null, "blur"),
                content: vxRule(true, null, "blur"),
                isDisplayed: vxRule(true, null, "blur"),
                isPinned: vxRule(true, null, "blur"),
            },

            init: {
                // selector: 'textarea',
                language_url: "/tinymce/langs/zh_CN.js", //引入语言包文件
                language: "zh_CN", //语言类型
                skin_url: "/tinymce/skins/ui/oxide", //皮肤：浅色
                // skin_url: '/tinymce/skins/ui/oxide-dark',//皮肤：暗色
                plugins: this.plugins, //插件配置
                toolbar: this.toolbar, //工具栏配置，设为false则隐藏
                // menubar: 'file edit',  //菜单栏配置，设为false则隐藏，不配置则默认显示全部菜单，也可自定义配置--查看 http://tinymce.ax-z.cn/configure/editor-appearance.php --搜索“自定义菜单”
                // fontsize_formats: "四号=16px 小四=14px 五号=18px 小五=12px'",
                toolbar_mode: "sliding",
                // fontsize_formats:
                //     "12px 14px 16px 18px 20px 22px 24px 28px 32px 36px 48px 56px 72px", //字体大小
                fontsize_formats:
                    "初号=56px 小初=48px 一号=37px 小一=32px 二号=29px 小二=24px 三号=21px 小三=20px 四号=18px 小四=16px 五号=14px 小五=12px 六号=10px 小六=9px 七号=7px 八号=6px", //字体大小
                font_formats:
                    "微软雅黑=Microsoft YaHei,Helvetica Neue,PingFang SC,sans-serif;苹果苹方=PingFang SC,Microsoft YaHei,sans-serif;宋体=simsun,serif;仿宋体=FangSong,serif;黑体=SimHei,sans-serif;Arial=arial,helvetica,sans-serif;Arial Black=arial black,avant garde;Book Antiqua=book antiqua,palatino;",
                height: 500, //注：引入autoresize插件时，此属性失效
                width: "100%",
                placeholder: "在这里输入文字",
                branding: false, //tiny技术支持信息是否显示
                resize: false, //编辑器宽高是否可变，false-否,true-高可变，'both'-宽高均可，注意引号
                // statusbar: false,  //最下方的元素路径和字数统计那一栏是否显示
                elementpath: false, //元素路径是否显示

                content_style: "img {max-width:100%;}", //直接自定义可编辑区域的css样式
                // content_css: '/tinycontent.css',  //以css文件方式自定义可编辑区域的css样式，css文件需自己创建并引入
                images_upload_url: '../../assets/folder.png',  //后端处理程序的url
                // images_upload_base_path: '/demo',  //相对基本路径--关于图片上传建议查看--http://tinymce.ax-z.cn/general/upload-images.php
                // 此处为图片上传处理函数，这个直接用了base64的图片形式上传图片，
                // 如需ajax上传可参考https://www.tiny.cloud/docs/configure/file-image-upload/#images_upload_handler
                images_upload_handler: (blobInfo, success, failure) => {
                    const img = "data:image/jpeg;base64," + blobInfo.base64();
                    success(img);
                },

                images_upload_handler: function (blobInfo, succFun, failFun) {
                    const formData = new FormData();
                    var file = blobInfo.blob(); //转化为易于理解的file对象 
                    formData.append('file', file);
                    httpService(
                        "/javaApi/upload/uploadFile", formData, "post"
                    ).then((data) => {
                        console.log("图片上传了", data.url);
                        const url = "https://wx.zhengzhong.cn" + data.url
                        // const url = "http://192.168.9.20" + data.url
                        succFun(url);

                    });

                },
                file_picker_types: 'image file media', // 允许上传的文件类型
                file_picker_callback: function (callback, value, meta) {
                    //文件分类
                    var filetype = '.jpg, .png, .pdf, .txt, .zip, .rar, .7z, .doc, .docx, .xls, .xlsx, .ppt, .pptx, .mp3, .mp4';
                    var input = document.createElement('input');
                    input.setAttribute('type', 'file');
                    input.setAttribute('accept', filetype);
                    input.click();
                    input.onchange = function () {
                        var file = this.files[0];
                        const formData = new FormData();
                        formData.append('file', file);
                        httpService(
                            "/javaApi/upload/uploadFile", formData, "post"
                        ).then((data) => {
                            console.log("图片上传了", data.url);
                            const url = "https://wx.zhengzhong.cn" + data.url
                            // const url = "http://192.168.9.20" + data.url
                            // succFun(url);
                            callback(url, { text: file.name, title: file.name });

                        });
                    };
                },

            },
        };
    },
    components: {
        IconPicture,
        ElConfigProvider,
        ElMessageBox, Stamp, Editor,
        ElMessage, Upload, bottomView,
    },
    setup() {
        return {
            locale: zhCn,
        };
    },
    mounted() {
        this.initTinymce();
        this.getListmy();
        // alert(this.$route.query.id)
        // alert(1)
        if (this.$route.query.id != undefined) {
            this.queryId = this.$route.query.id
            this.queryNotice(this.queryId)
        }
    },
    watch: {
    },
    methods: {
        initTinymce() {
            tinymce.init({});
        },
        onClick(e) {
            this.$emit("onClick", e, tinymce);
        },
        searchEnter: function (e) {
            var keyCode = window.event ? e.keyCode : e.which;
            var val = e.target.value;
            if (keyCode == 13 && val) {
                this.getListmy();
            }
        },
        changeTime(value) {
            this.addPbArticleForm.publishDate = formatTime(value)
        },
        changeSwitch(value) {
            // console.log(value);
            // value == true ? this.addPbArticleForm.isDisplayed = 1 : this.addPbArticleForm.isDisplayed = 0
        },
        changeSwitch1(value) {
            // console.log(value);
            // value == true ? this.addPbArticleForm.isPinned = 2 : this.addPbArticleForm.isPinned = 1
        },
        add() {
            console.log(this.addPbArticleForm);
            if (!this.addPbArticleForm.title) {
                return ElMessage.error({ message: '标题不能为空', offset: 60, })
            } else if (!this.addPbArticleForm.summary) {
                return ElMessage.error({ message: '简介不能为空', offset: 60 })
            } else if (!this.addPbArticleForm.content) {
                return ElMessage.error({ message: '详细内容不能为空', offset: 60 })
            } else {
                let params = new FormData()
                this.addPbArticleForm.isPinned == true ? this.addPbArticleForm.isPinned = 2 : this.addPbArticleForm.isPinned = 1
                this.addPbArticleForm.isDisplayed == true ? this.addPbArticleForm.isDisplayed = 1 : this.addPbArticleForm.isDisplayed = 2
                params.append("title", this.addPbArticleForm.title)
                params.append("content", this.addPbArticleForm.content)
                params.append("isPinned", this.addPbArticleForm.isPinned)
                params.append("isDisplayed", this.addPbArticleForm.isDisplayed)
                params.append("summary", this.addPbArticleForm.summary)
                params.append("sortNum", 100)
                params.append("publishDateStr", this.addPbArticleForm.publishDate)
                // params.append("departmentIds", this.addPbArticleForm.departmentIds)
                // params.append("teacherNumbers", this.addPbArticleForm.teacherNumbers)

                if (this.queryId) {
                    params.append("id", this.queryId)
                    httpService("/javaApi/messages/edit", params, "post").then(
                        (data) => {
                            console.log(data);
                            if (data.code == 200) {
                                ElMessage.success("修改成功");
                                // this.$router.push({ path: '/noticeIndexView/noticePublishListView' })
                                this.$router.go(-1)
                                this.clear()
                            } else {
                                ElMessage.error("修改失败");
                            }
                        })
                }
            }
        },
        clear() {
            this.addPbArticleForm.title = ""
            this.addPbArticleForm.publishDate = ""
            this.addPbArticleForm.summary = ""
            this.addPbArticleForm.content = ""
            this.addPbArticleForm.departmentIds = ""
            this.addPbArticleForm.teacherNumbers = ""
            this.addPbArticleForm.isDisplayed = 1
            this.addPbArticleForm.isPinned = 2
        },
        queryNotice(id) {
            const that = this
            httpService("/javaApi/messages/queryById", { id: id }, "get").then(
                (data) => {
                    this.addPbArticleForm = data
                    this.addPbArticleForm.isPinned == 1 ? this.addPbArticleForm.isPinned == false : this.addPbArticleForm.isPinned == true
                    this.addPbArticleForm.isDisplayed == 1 ? this.addPbArticleForm.isDisplayed = true : this.addPbArticleForm.isDisplayed = false
                    // this.keys = [148, 96, 142, 90, 69, 89, 88, 87, 70, 86, 85, 84, 83, 82, 128, 80, 77, 78, 79, 105, 139, 152, 151, 1, 81];
                    // const that = this
                    setTimeout(function () {
                        that.keys.forEach((value) => {
                            that.$refs.tree.setChecked(value, true, false)
                        })
                    }, 0);
                })
        },
        getListmy() {
            httpService("/javaApi/baseTeacherDepartment/teacherTree", {}, "get").then(
                (data) => {
                    const arr = this.editData(data)
                })
        },
        editData(valueData) {
            setTimeout(() => {
                const convertedData = [];
                for (const schoolKey in valueData) {
                    const school = valueData[schoolKey];
                    const schoolObject = {
                        label: school.name,
                        value: schoolKey,
                        children: [],
                    };
                    for (const departmentKey in school.departments) {
                        const department = school.departments[departmentKey];
                        const departmentObject = {
                            label: departmentKey,
                            value: department.departmentId,
                            departmentName: department.departmentName,
                            departmentId: department.departmentId,
                            children: [],
                        };
                        department.teachers.forEach(teacher => {
                            const teacherObject = {
                                teacherName: teacher.teacherName,
                                teacherNumber: teacher.teacherNumber,
                                label: teacher.teacherName,
                                value: teacher.teacherNumber,
                            };
                            departmentObject.children.push(teacherObject);
                        });
                        schoolObject.children.push(departmentObject);
                    }
                    convertedData.push(schoolObject);
                }
                convertedData.unshift({
                    label: "全校",
                    value: "0",
                    children: []
                })
                const dataArr = JSON.stringify(convertedData)
                this.allTeacherList = convertedData
                this.allList = dataArr
            }, 0);
        },


        handleCheckChange(data, checked) {
            let flag = false
            let flagArr = []
            flagArr = this.allCheckedNodes.filter(item => item.value === data.value)
            if (flagArr.length > 0) {
                flag = true
            } else {
                flag = false
            }

            if (!flag) {
                this.checkedNodes.push(data);
                this.checkedNodes = JSON.parse(JSON.stringify(this.checkedNodes))
                this.allCheckedNodes = [...checked.checkedNodes]
            } else {
                this.checkedNodes = this.removeNodeByValue(this.checkedNodes, data.value)
                this.allCheckedNodes = [...checked.checkedNodes]
            }
            this.changeTeacher(this.checkedNodes)

        },

        changeTeacher(treeData) {
            let departArr = []
            let teacherArr = []
            treeData.forEach(item => {
                if (item.label == "全校") {
                    this.addPbArticleForm.departmentIds = ""
                    this.addPbArticleForm.teacherNumbers = ""
                    return
                } else if (item.label == schoolName) {
                    departArr = departArr.concat(item.children)
                } else if (item.label == schoolName1) {
                    departArr = departArr.concat(item.children)
                } else if (item.hasOwnProperty('departmentName')) {
                    departArr.push(item)
                } else if (item.hasOwnProperty('teacherName')) {
                    teacherArr.push(item)
                }
            })

            departArr = departArr.filter(item1 => {
                return this.allCheckedNodes.some(item2 => item2.label === item1.label && item2.value === item1.value);
            });
            teacherArr = teacherArr.filter(item1 => {
                return this.allCheckedNodes.some(item2 => item2.label === item1.label && item2.value === item1.value);
            });


            // console.log(110, departArr, "----", teacherArr);
            if (departArr.length > 0) {
                this.addPbArticleForm.departmentIds = departArr.map(item => item.departmentId).join(",")
            } else {
                this.addPbArticleForm.departmentIds = ""
            }
            if (teacherArr.length > 0) {
                this.addPbArticleForm.teacherNumbers = teacherArr.map(item => item.teacherNumber).join(",")
            } else {
                this.addPbArticleForm.teacherNumbers = ""
            }
            const school = this.allCheckedNodes.filter(item => item.label == "全校")
            if (school.length > 0) {
                this.addPbArticleForm.departmentIds = ""
                this.addPbArticleForm.teacherNumbers = ""
            }
            // console.log(1, this.addPbArticleForm.departmentIds, "----", this.addPbArticleForm.teacherNumbers);
        },

        removeNodeByValue(tree, valueToRemove) {
            return tree.filter(node => {
                if (node.children) {
                    node.children = this.removeNodeByValue(node.children, valueToRemove);
                }
                return node.value !== valueToRemove;
            });
        },


    },
};
</script>
<style scoped>
.el-main {
    padding: 0px;
}

.teacher-content {
    width: 100%;
}

.app-table {
    background: #eff3f5;
    /* padding: 5px 10px 10px; */
    margin-top: 20px;
    padding-bottom: 70px;
    position: relative;
}

.app-body {
    background: white;
    padding: 20px 20px 10px 20px;
    margin-bottom: 10px;
    min-height: calc(100vh - 244px);
}

.app-search {
    border-top: 1px solid #dedede;
    margin-top: 20px;
    background-color: #fff;
    padding: 20px 15px 0;
}

.app-separator {
    padding-top: 10px;
    padding-bottom: 20px;
    padding-left: 10px;
}

.app-body {
    background: white;
    padding: 20px 20px 10px 20px;
    margin-bottom: 10px;
}

.flex {
    display: flex;
    align-items: center;
}

.title_box {
    width: 100%;
    height: 43px;
    /* background-color: brown; */
}

.title_box .titleInput {
    width: calc(100% - 4px);
    height: 100%;
    text-align: center;
    border-radius: 5px;
    border: 1px solid #DBDEE5;
    font-size: 18px;
    outline: none;
}

.title_box .titleInput::placeholder {
    color: #001E34;
    font-size: 18px;
    font-weight: bold;
}

.intro_box {
    margin-top: 15px;
    width: 100%;
    height: 200px;
    border: 1px solid #DBDEE5;
    border-radius: 5px;
    position: relative;
}

.introBtn {
    width: 113px;
    height: 35px;
    border: 1px solid #CACED6;
    border-radius: 5px;
    position: absolute;
    left: 10px;
    top: 15px;
    justify-content: center;
    color: #001E34;
}

.introBtn img {
    width: 20px;
    margin-right: 8px;
}

.intro_box textarea {
    width: calc(100% - 24px);
    height: 128px;
    outline: none;
    border: none;
    resize: none;
    border-radius: 5px;
    margin-top: 68px;
    margin-left: 10px;
    font-size: 14px;
}

.intro_box textarea::placeholder {
    color: #5E6B75;
    font-size: 14px;
}

.contain {
    width: calc(100% - 20px);
    height: 43px;
    border: 1px solid #DBDEE5;
    border-radius: 5px;
    margin-top: 10px;
    padding: 0 10px;
    font-size: 14px;
    color: #001E34;
    overflow: hidden;
}

.switchBox {
    margin-right: 50px;
}

.switchBox p {
    margin-right: 10px;
    white-space: nowrap;
}

.add_img {
    width: 18px;
    margin-right: 10px;
}

.editorBox p {
    color: #001E34;
    font-size: 16px;
}

.publish {
    width: 130px;
    height: 40px;
    background-color: #007EFF;
    border-radius: 5px;
    border: none;
    /* position: absolute; */
    position: fixed;
    bottom: 20px;
    left: 50%;
    transform: translateX(-50%);
    z-index: 99;
    color: #fff;
    font-size: 14px;
}
</style>
